package com.aqie.medium.backtrack;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 216 所有相加之和为 n 的 k 个数的组合。组合中只允许含有 1 - 9 的正整数，并且每种组合中不存在重复的数字
 */
public class CombinationSum3 {
    private List<List<Integer>> ans = new ArrayList<>();

    public List<List<Integer>> combinationSum3(int k, int n) {
        traceBack(k, n,0,1, new LinkedList<>());
        return ans;
    }

    private void traceBack(int k, int n, int sum, int begin, LinkedList<Integer> list) {
        if (k == 0){
            if (n == sum){
                ans.add(new ArrayList<>(list));
            }

            return;
        }
        for (int i = begin; i < 10; i++){
            list.add(i);
            traceBack(k-1, n, sum + i, i + 1, list);
            list.removeLast();
        }
    }
}
